package cn.uniquesoft.api;

import cn.uniquesoft.service.IArticleService;
import cn.uniquesoft.service.IUserService;
import cn.uniquesoft.util.ContextUtil;
import cn.uniquesoft.util.DateUtil;
import cn.uniquesoft.util.FileUtil;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.ArticleVO;
import cn.uniquesoft.vo.UserVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2018-11-21 14:59:24
 * @description: app 文章
 **/
@RestController
@RequestMapping(value = "/api/article")
public class ApiArticleController {
    @Value("${resource.pagesize}")
    private int pagesize;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IUserService userService;
    private static List<String> fileTypes = new ArrayList<String>();

    static {
        fileTypes.add(".jpg");
        fileTypes.add(".jpeg");
        fileTypes.add(".bmp");
        fileTypes.add(".gif");
        fileTypes.add(".png");
    }
    /**
     * 首页动态信息
     */
    @RequestMapping(value = "/dtxx")
    @ResponseBody
    public String dtxx() {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(ArticleVO.class, "iid", "ctitle", "dmodify");
        List<ArticleVO> list = this.articleService.appDtxx();
        String str = JSON.toJSONString(list, filter);

        return str;
    }
    /**
     * 企业动态列表页信息
     */
    @RequestMapping(value = "/getCompanyDynamic")
    @ResponseBody
    public  String  getCompanyDynamic(int iid,String option,int itype ) {

        List<ArticleVO> itemList = new ArrayList<>();
        ArticleVO item = new ArticleVO();
        item.setIid(iid);
        item.setPageSize(this.pagesize);
        item.setArticletypeiid(itype);
        if(option.equals("down")){
            if(iid==0){
                itemList =   this.articleService.getItemsFirst(item);
            }else{
                itemList =   this.articleService.findListDown(item);
            }

        }else{
            itemList =   this.articleService.findListUp(item);
        }
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(ArticleVO.class, "iid", "ctitle", "curl","dcreator");
        String str = JSON.toJSONString(itemList, filter);
        
        return str;

    }
    /**
     * 分组获取每组前四个动态
     */

    @RequestMapping(value = "/getArticle")
    @ResponseBody
    public List<ArticleVO> getArticle() {
        List<ArticleVO> list = this.articleService.getGroup();
        return list;
    }

    /**
     * 根据类型取审核通过的第一条数据
     * @param articletypeiid
     * @return
     */
    @RequestMapping(value ="/getFirstItemChecked")
    public String getFirstItemChecked(int articletypeiid){
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(ArticleVO.class, "iid", "curl");
        ArticleVO articleVO = this.articleService.getFirstItemChecked(articletypeiid);
        String str = JSON.toJSONString(articleVO, filter);
        return str;
    }

    @RequestMapping(value = "/toSaveArticle")
    @ResponseBody
    public AnswerVO toSaveArticle(ArticleVO item) {
        AnswerVO answerVO = new AnswerVO();
        UserVO userVO = this.userService.findOneById(item.getIcreator());
        if(3 == userVO.getIusertype()){
            item.setArticletypeiid(1);
        }else{
            item.setArticletypeiid(2);
        }
        item.setIusertype(userVO.getIusertype());
        item.setIorgname(userVO.getIorgname());
        item.setIcreator(userVO.getIid());
        item.setDcreator(new Date());
        item.setCcreator(userVO.getCname());
        int count = this.articleService.save(item);
        if (count > 0) {
            answerVO.setSuccess(true);
            answerVO.setMsg("保存成功！等待审核");
            //生成html文件用于app调用
            //存储路径
        String htmlPath = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/files/tw");
        String fileName = "tw_" + userVO.getIid() + "_" + item.getIid() + ".html";
        String ccontent = item.getCcontent();
        FileUtil.parseHtml(htmlPath, item.getCtitle(), fileName, ccontent);
        item.setCurl(fileName);
        this.articleService.updateUrl(item);
        } else {
            answerVO.setSuccess(false);
            answerVO.setMsg("操作失败！请联系管理员");
        }
        return answerVO;
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public String save(MultipartFile upload,HttpServletRequest request) throws Exception {
        System.out.println(upload.getOriginalFilename());
        String fileName = null;
        if (upload != null) {
            // 取得当前上传文件的文件名称
            String myFileName = upload.getOriginalFilename();
            // 如果名称不为“”,说明该文件存在，否则说明该文件不存在

            String DirectoryName = "files/pic";
            if (myFileName.trim() != "") {
                // 获得图片的原始名称
                String originalFilename = upload.getOriginalFilename();
                // 获得图片后缀名称,如果后缀不为图片格式，则不上传
                String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

                // 获得上传路径的绝对路径地址(/upload)-->
                String realPath = request.getSession().getServletContext().getRealPath("/" + DirectoryName);
                System.out.println(realPath);
                // 如果路径不存在，则创建该路径
                File realPathDirectory = new File(realPath);
                if (realPathDirectory == null || !realPathDirectory.exists()) {
                    realPathDirectory.mkdirs();
                }
                // 重命名上传后的文件名 tw111112323.jpg
                fileName = "tw" + DateUtil.date2String(new Date(),DateUtil.yyyyMMddHHmmss_EN) + suffix;
                // 定义上传路径 .../upload/111112323.jpg
                File uploadFile = new File(realPathDirectory + "\\" + fileName);
                System.out.println(uploadFile);
                upload.transferTo(uploadFile);
            }
        }
        return fileName;
    }


}
